package com.zero.guava.samples.FutureCallback;

import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用FutureCallback
 * FutureCallback 接口提供了onSuccess 和onFailure 方法，用于接收任务执行的结果，
 * 通过FutureCallback我们可以方便的在任务执行成功或失败后进行其他的处理，但有些时候我们想主动的设置任务 的返回值
 */
public class FutureCallbackDemo2 {

    @Test
    public void testFutureCallback() throws ExecutionException, InterruptedException {

        // 创建一个线程缓冲池Service
        ExecutorService executor = Executors.newCachedThreadPool();
        //创建一个ListeningExecutorService实例
        ListeningExecutorService executorService = MoreExecutors.listeningDecorator(executor);
        //提交一个可监听的线程
        ListenableFuture<String> futureTask  = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return "Task completed";
            }
        });

        FutureCallbackImpl2 callback = new FutureCallbackImpl2();

        //线程结果处理回调函数
        Futures.addCallback(futureTask, callback);
        System.out.println( callback.getCallbackResult().get());
        //如果callback中执行的是比较费时的操作，Guava建议使用以下方法。
        Futures.addCallback(futureTask,callback,executorService);
        System.out.println( callback.getCallbackResult().get());

    }
}
